package com.wx.spider.common.util.randomport;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class ServerPortUtils {

    public static int getAvailablePort(Integer min, Integer max, Set<Integer> portSet) {
        max = max == null || max > 65535 ? 65535 : max;
        min = min == null || min < 5000 ? 5000 : min;


        Random random = new Random();

        int port = random.nextInt(max)%(max-min+1) + min;
        boolean using = NetUtils.isLoclePortUsing(port);
        if (using) {
            if(portSet == null){
                portSet = new HashSet<Integer>();
            }else{
                if(portSet.size() > (max-min)){
                    throw new RuntimeException("接口范围已经用完了！");
                }
            }
            portSet.add(port);

            return getAvailablePort(min, max, portSet);
        } else {
            return port;
        }
    }

}
